import { ref, Ref } from "vue";

class PDFViewer {
    Toolbar: Toolbar;

    constructor(frame: HTMLIFrameElement) {
        frame.contentDocument!.querySelector('#viewerContainer')?.classList.add('pdf-viewer-container');

        this.Toolbar = new Toolbar(frame.contentDocument!);
    }
}

class Toolbar {
    PresentationMode: HTMLButtonElement;
    OpenFile: HTMLButtonElement;
    Print: HTMLButtonElement;
    Download: HTMLButtonElement;
    ViewBookmark: HTMLLinkElement;

    constructor(document: Document) {
        this.PresentationMode = document.querySelector('#presentationMode')!;
        this.OpenFile = document.querySelector('#openFile')!;
        this.Print = document.querySelector('#print')!;
        this.Download = document.querySelector('#download')!;
        this.ViewBookmark = document.querySelector('#viewBookmark')!;
    }

    public Update(options: ToolbarOptions): void {
        if (options.PresentationMode ?? true) {
            this.PresentationMode.classList.remove('hidden');
        } else {
            this.PresentationMode.classList.add('hidden');
        }

        if (options.OpenFile ?? true) {
            this.OpenFile.classList.remove('hidden');
        } else {
            this.OpenFile.classList.add('hidden');
        }

        if (options.Print ?? true) {
            this.Print.classList.remove('hidden');
        } else {
            this.Print.classList.add('hidden');
        }

        if (options.Download ?? true) {
            this.Download.classList.remove('hidden');
        } else {
            this.Download.classList.add('hidden');
        }

        if (options.ViewBookmark ?? true) {
            this.ViewBookmark.classList.remove('hidden');
        } else {
            this.ViewBookmark.classList.add('hidden');
        }
    }
}

class ToolbarOptions {
    PresentationMode?: boolean;
    OpenFile?: boolean;
    Print?: boolean;
    Download?: boolean;
    ViewBookmark?: boolean;
}

/**
 * PDF查看器
 */
export default class PDFViewerComponent {
    private static instance: PDFViewerComponent = new PDFViewerComponent();
    /**
     * PDF查看器
     */
    public static get Default(): PDFViewerComponent {
        return this.instance;
    }

    constructor() {
        window.addEventListener('unload', this.Dispose.bind(this));
    }

    Dispose() {
        window.removeEventListener('unload', this.Dispose);
    }

    public Src: Ref<string> = ref('/电路图.pdf');

    private viewers = new Map<string, PDFViewer>();

    public AddViewer(name: string, element: HTMLIFrameElement): void {
        this.viewers.set(name, new PDFViewer(element));
    }

    public RemoveViewer(name: string): boolean {
        return this.viewers.delete(name);
    }

    public UpdateToolbar(name: string, options: ToolbarOptions): void {
        const viewer = this.viewers.get(name);
        if (viewer == null) {
            return;
        }

        viewer.Toolbar.Update(options);
    }
}